<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Middleware;

use App\Model\User;
use App\Services\JwtTokenService;
use Exception;
use Hyperf\Context\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AuthMiddleware implements MiddlewareInterface
{
    public function __construct(protected ContainerInterface $container, protected JwtTokenService $jwtTokenService)
    {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $token = $request->getHeader('Authorization')[0] ?? '';
        $post = $request->getParsedBody();
        $query = $request->getQueryParams();
        $params = array_merge($post, $query);
        $source = $params['source'] ?? '';
        // var_dump($source);
        if (strpos($token, 'Bearer') === 0) {
            $token = trim(substr($token, 6));
        }
        $payload = $this->jwtTokenService->verifyToken($token);
        if (! $payload) {
            throw new Exception('token error');
        }
        if (!empty($source) && strtoupper($payload['source']) != strtoupper($source)){
            throw new Exception('token source error');
        }

        Context::set('source', $payload['source']);
        Context::set('uid', $payload['id']);
        return $handler->handle($request);
    }
}
